#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os

from docx import Document
from util import Util
from write.AbstractWrite import AbstractWrite


class ShipReviewFrom(AbstractWrite):
	def __init__(self):
		super().__init__()

	def setDic(self, cargoTextDic, cargoUnderlineDic, shipTextDic, shipUnderlineDic):
		self.cargoTextDic = cargoTextDic
		self.cargoUnderlineDic = cargoUnderlineDic
		self.shipTextDic = shipTextDic
		self.shipUnderlineDic = shipUnderlineDic

	def write(self):
		oldPath, newPath = self._getPath("租船合同重要条款核查表")
		doc = Document(oldPath)

		# 读取第1个表格
		table = doc.tables[0]

		# 修改船名，保留格式改文字
		runs = table.cell(1, 1).paragraphs[0].runs
		[run.clear() for run in runs[1:]]
		runs[0].text = str(self.shipUnderlineDic["航次"][0])

		# 修改航次
		runs = table.cell(2, 4).paragraphs[0].runs
		# del runs[1:]
		[run.clear() for run in runs[1:]]
		runs[0].text = str(self.shipUnderlineDic["航次"][1])

		# 修改客户名
		runs = table.cell(4, 2).paragraphs[0].runs
		[run.clear() for run in runs[1:]]
		runs[0].text = str(self.shipTextDic["乙方"])

		# 修改日期
		run = Util.getRun(table.cell(56, 1).paragraphs, "时间：")
		run.text = run.text.replace('时间：', '时间：' + self.shipTextDic["签约日期"])

		doc.save(newPath)

	def _getPath(self, modelName):
		oldName = ""
		outputPath = os.path.join(self.outputDir,
		                          "{shipName}V{voyage}".format(shipName=self.shipUnderlineDic["航次"][0],
		                                                       voyage=self.shipUnderlineDic["航次"][1]))
		if not os.path.exists(outputPath):
			os.makedirs(outputPath)
		files = os.listdir(self.modelPath)
		files.sort()

		for file in files:
			if os.path.splitext(file)[0] == modelName:
				oldName = file
		newname = "船附件3：{shipName}V{voyage}{oldname}".format(shipName=self.shipUnderlineDic["航次"][0],
		                                                        voyage=self.shipUnderlineDic["航次"][1],
		                                                        oldname=oldName)
		newPath = os.path.join(outputPath, newname)
		oldPath = os.path.join(self.modelPath, oldName)

		return oldPath, newPath
